﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace thousandClear.Util.Media
{
    public class ImageResolver
    {
        public Image Base64ToImage(string base64Str)
        {
            byte[] imageBytes = Convert.FromBase64String(base64Str);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            ms.Write(imageBytes, 0, imageBytes.Length);
            Image img = Image.FromStream(ms, true);

            return img;
        }

        public void SaveBase64(string base64Str, string path, string fileName)
        {
            Image img = Base64ToImage(Format(base64Str));

            if(!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            img.Save(path + "\\" + fileName);
        }

        public string GetExt(string base64Str)
        {
            int firstIdx = base64Str.IndexOf('/') + 1;
            int lastIdx = base64Str.IndexOf(';');

            string extName = base64Str.Substring(firstIdx, lastIdx - firstIdx);

            return extName;
        }

        public string Format(string base64Str)
        {
            int idx = base64Str.LastIndexOf(',') + 1;
            int length = base64Str.Length - idx;
            base64Str = base64Str.Substring(idx, length);
            return base64Str;
        }
    }
}
